/**
 * 远光Gris平台3.0版本 http://www.ygsoft.com/ Grace [Gris Application Cloud-Computing
 * Extension]
 * 
 * 导入结果展现
 * 
 * 变更版本：
 * wuhuating@ygsoft.com 2012-3-1 创建
 */

define(["jquery","ecp.utils","ecp.component.dialog","qzz.querygrid","ecp.utils.i18n"],function($, utils, $window, grid, i18n){
	var tabLiStr = '<li class="{active}"><a href="{id}" data-toggle="tab">{text}</a></li>';
	var tabDivStr = '<div class="tab-pane {active}" id="{id}" style="height:370px;"><table id="{tableId}"></table></div>';
	var content = '<div class="page-container"><ul class="nav nav-tabs nav-line"></ul></div><div class="tab-content padding_20" style="height:370px;"></div>';
	var ImportResult = function(){
		
	}
	
	/**
	 * 通过原型定义相关方法，比如渲染、赋值等等.
	 */
	ImportResult.prototype = {
		/**
		 * 生成表格
		 * @param resultTableId 表格id
		 * @param option 表格参数
		 */
		createQzzGrid : function(tabId, opt) {
			var w = parseFloat(opt.width),
				h = parseFloat(opt.height) - 200,
				p = opt.pager,
				mw = w - 250;
			var grid = $("#" + tabId).qzzquerygrid({
	              "pager": opt.pager,
	              "Align":"alClient",
	              "width": w,
	              "height": h,
	              "colNames": [i18n.import.rowNum,i18n.import.checkMsg],
	              "colModels":[
	                    {"name":"rowIndex","width":60,"align":"center"},
	                    {"name":"msg","width":mw,"showHint":true}
	              ]
	        });
		},

		/**
		 * 添加页签
		 * @param result 表格添加的数据
		 * @param option 表格属性
		 */
		addSheetTabs : function(result, opt) {
			if(!result){return;}
			var container = opt.container,
				tabs = $("#importResultTabs",container),
				exportResultBtn = $("#exportResultBtn",container);
			if(opt.hideBtn && result && result.length>0 && (result[0].totalFailure >0 || result[0].totalSuccess>0)){
				$("#importResult",container).text((result[0].totalSuccess ? i18n.import.success + "：" + result[0].totalSuccess+ i18n.import.strip+"，" : "") + i18n.import.error + "："+result[0].totalFailure + i18n.import.strip + "，");
			}
			exportResultBtn.bind("click",function(){
				var grids = $("table[id]", container);
				var option = {};
			   	option.fileName = i18n.import.checkMsg+".xlsx";
			    option.dataList =[];
			    var taberrors = $("#importResultTabs", container);
			    grids.each(function(i,grid){
			    	var testdata = grid.p.data;
					if(testdata!=null && testdata.length>0){
						var exportdata =[];
						var tabName = taberrors.text() || i18n.import.checkMsg +i;
						testdata.each(function(obj,i){var datas = [];datas.push(obj["index"]);datas.push(obj["rowIndex"]);datas.push(obj["msg"]);exportdata.push(datas);});
						option.dataList.push({"tabName" : tabName, "beforeData":[[{d:i18n.import.num,s:"h|c"},{d:i18n.import.rowNum,s:"h|c"},{d:i18n.import.checkMsg,s:"h|c"}]], "userData" : exportdata });
					}
			    });
				
				$.ecp.Document.exportFile(option);
			});
			var isSingleFile = false;
			if (result.length == 1) {
				isSingleFile = true;
			}
			var $navContainer = $(".nav-tabs", container);
			var $tabContainer = $(".tab-content", container);
			var firstFlag=true;
			for (var i = 0,sz = result.length; i < sz; i++) {
				//0表示验证通过。
				if (result[i].code === 0) continue;
				
				var sheets = result[i].sheetResults;
				if (!sheets) continue;
				
				var sheets = result[i].sheetResults;
				for (var key in sheets) {
					var sheet = sheets[key];
					var rows = sheet.rowResults;
					if (!rows){ continue;}

					var tabName = sheet.sheetName;
					if (!isSingleFile) {
						tabName += ' (' + result[i].fileName + ')';
					}
					var tabId = "file" + i + "sheet" + key;
					var navStr = tabLiStr.replace("{id}", tabId+"_nav").replace("{text}",tabName).replace("{active}", firstFlag ? "active" : "");
					var tabStr = tabDivStr.replace("{id}", tabId+"_nav").replace("{tableId}", tabId).replace("{active}", firstFlag ? "active" : "");
					firstFlag = false;
					$navContainer.append(navStr);
					$tabContainer.append(tabStr);
					
					this.createQzzGrid(tabId, opt);
					rows = rows.sortBy("rowIndex");
					var $tabId = $("#" + tabId, container);
					var res = [];
					for (var n = 0, rsz = rows.length; n < rsz; n++) {
						var row = rows[n];
						row.rowIndex = row.rowIndex + 1;
						if(row.msg){
							row.msg = row.msg.replaceAll("<br>","<br>\n");
						}
						res.push(row);
//						$tabId.jqGrid('addRowData', n + 1, row);
//						$tabId.qzzquerygrid(true).addEcpRowData(row);
					}
					$tabId.qzzquerygrid(true).value(res);
				}
			}
		},
		
		/**
		 *  显示导入结果。
		 *  @param result 
		 *  @parma option 窗口参数 
		 */
		showResult : function(result, opt, callback) {
			var me = this;
			opt = opt || {};
			var resultOpt = {
				width : "700px",
				height : "450px",
				title : i18n.import.aginImport,
				content: content
				//url: "/grm/ecp/webcore/components/import/importResult.html"
			};
			$.extend(resultOpt, opt, {
                callback:function(container){
                	me.container = container;
                	me.addSheetTabs(result, {
    					width : resultOpt.width,
    					height : resultOpt.height,
    					container: container,
    					pager:true,
    					hideBtnAndInfo : opt.hideBtnAndInfo,
    					hideBtn : opt && opt.hideBtn
    				});
                	//绑定页签点击事件切换页签
                	$(".page-container", container).off("click").on("click", "ul>li", function(){
                		var $me = $(this);
            			$me.parent().find("li").removeClass("active");
            			$me.addClass("active");
                		//内容处理选中
                		$(".tab-content", container).find(".tab-pane").removeClass("active");
                		$("#"+$me.find("a").attr("href"), container).addClass("active");
                	})
                	
                },
                dialogHide:function(){
                	if($.isFunction(opt.callback)){
                		opt.callback.call(opt._this,val,result,opt.scheme);
                	}
                },
                showCloseButton:false,
                offClick :true,  //取消点击非模态窗位置关闭窗口
                otherButtons:[i18n.import.close,i18n.import.exportCheckResult,i18n.import.keyupImport],  //增加两个按钮
                otherButtonStyles:['btn-link','btn-link','btn-primary'], //按钮样式,
                clickButton:function(sender, modal, index){
                	if(index == 0){ 
                		//关闭
                		modal.modal("hide");
                	}else if(index == 1){
                		//导出校验结果
                		require(["ecp.export"],function(ecpExport){
                			var option = {};
                			option.fileName = i18n.import.checkMsg;
                      		option.type="xlsx";
                			option.dataList = [];
                			var container = me.container;
                			var $lis = $(".page-container", container).find("li");
                			var $tabPane = $(".tab-content", container).find(".tab-pane");
                			var primaryKeys =['index','rowIndex','msg'];
                      		var primaryDt = [{s:"c",dt:'string'},{s:"c",dt:'string'},{s:"l",dt:'string'}];
                			if($lis.length === 0 || $tabPane.length === 0){
                				return;
                			}
                      		$lis.each(function(i,li){
                				var $me = $(this);
                				var href = $me.find("a").attr("href");
                				var ordata = $("#"+href.substring(0,href.indexOf("_"))).qzzquerygrid(true).value();
                				if(utils.isEmpty(ordata)){
                					ordata = [];
                				}
//                				var newData = $.extend(true,[],ordata);
                				$.each(ordata,function(i,obj){
                					this.index = i+1;
                					//过滤掉表格信息中的<br>
                					if(this.msg && this.msg.indexOf("<br>") >= 0){
                						this.msg = this.msg.replaceAll("<br>","");
                					}
                				})
                				var userData = utils.getExportData(primaryKeys,ordata,primaryDt);
                				option.dataList.push({
                					tabName: $me.text(),
                					header: [i18n.import.num, i18n.import.rowNum, i18n.import.checkMsg],
                					userData: userData
                				})
                			})
                			ecpExport.doExport(option);
                		})
                	}else{
                		//继续导入
                		callback();
                		modal.modal("hide");
                	}
                }
			});
			this.winContainer = $window.window(resultOpt);
		}
	}
	
	return {
		showImportResult : function(r, opt, callback) {
			var impr = new ImportResult();
			impr.showResult(r, opt, callback);
		}
	}
})